package common

import (
	"crypto/rand"
	"fmt"
	"math/big"
	"os"
	"path"
	"strconv"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

var File_Max_Upload_Size int64 = 8 << 20

var File_Upload_type = map[string]bool{"jpg": true, "png": true, "jpeg": true, "gif": true, "bmp": true, "webp": true, "mp4": true, "zip": false, "rar": true}

func init() {

}
func Upload_file(c *gin.Context) {
	fileurl := ""
	file, err := c.FormFile("file")
	if err != nil {
		c.String(500, "上传文件错误"+err.Error())
		return
	}
	file_type := file.Header.Get("Content-type")
	file_type_arr := strings.Split(file_type, "/")
	val, ok := File_Upload_type[file_type_arr[1]]
	if !ok || !val {

		c.JSON(500, gin.H{
			"code": 500,
			"msg":  "文件类型无法上传" + file_type,
		})
		return
	}
	if File_Max_Upload_Size < file.Size {
		c.JSON(500, gin.H{
			"code": 500,
			"msg":  "上传文件不可大于" + strconv.FormatInt(File_Max_Upload_Size>>20, 10) + "MB",
		})
		return
	}
	randNum, err := rand.Int(rand.Reader, big.NewInt(100))
	if err != nil {
		fmt.Println("错误随机数")
	}
	pathYear := time.Now().Format("200601")
	pathDay := time.Now().Format("20060102")
	filepath := "./upload/" + (pathYear) + "/" + (pathDay)

	/*重新设置*/
	// os.Stat(filepath)
	err = os.MkdirAll(filepath, os.ModePerm)
	if err != nil {
		c.JSON(500, gin.H{
			"code": 500,
			"msg":  "创建文件夹错误" + err.Error(),
		})
		return
	}
	newfileName := time.Now().UnixNano()

	filepath += "/" + strconv.FormatInt(newfileName, 10) + randNum.String() + path.Ext(file.Filename)
	fileurl = strings.Replace(filepath, "./", "/", 1)

	err = c.SaveUploadedFile(file, filepath)
	if err != nil {
		c.JSON(500, gin.H{
			"code": 500,
			"msg":  "上传文件错误!" + err.Error(),
		})
		return
	}
	data := map[string]interface{}{
		"path": filepath,
		"url":  ApiURL + fileurl,
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "上传成功",
		"data": data,
	})
}

//多文件上传

func Upload_files(c *gin.Context) {

	form, err := c.MultipartForm()

	if err != nil {
		fmt.Println(err.Error())
	}
	success_count := 0
	files := form.File["files"]
	pathYear := time.Now().Format("200601")
	pathDay := time.Now().Format("20060102")
	filepath := "./upload/" + (pathYear) + "/" + (pathDay)
	os.MkdirAll(filepath, os.ModePerm)
	path_slice := make([]string, 0)
	for _, file := range files {

		if File_Max_Upload_Size < file.Size {
			continue
		}

		filepath_save := filepath + ("/" + file.Filename)
		fileurl := strings.Replace(filepath_save, "./", "/", 1)

		err := c.SaveUploadedFile(file, filepath_save)
		if err == nil {
			path_slice = append(path_slice, (ApiURL + fileurl))
			success_count++
		} else {
			fmt.Println("错误：" + err.Error())
		}

	}

	if success_count <= 0 {
		c.JSON(500, gin.H{
			"msg":           "上传失败",
			"success_count": success_count,
		})
		return
	}

	c.JSON(200, gin.H{
		"msg":           "上传成功",
		"success_count": success_count,
		"path_slice":    path_slice,
	})
	return
}
